#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangXjwwezzqrmzfF363Policy(BaseTaxPolicySpider):
    name = 'xinjiang_xjwwezzqrmzf_f363_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "新疆维吾尔自治区"  # 取表格
    county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, url in [
            ['新疆维吾尔自治区人民政府', 'https://www.xinjiang.gov.cn/xinjiang/zfl/zfxxgk_zhengce_list.shtml'],
            ['新疆维吾尔自治区人民政府', "https://www.xinjiang.gov.cn/xinjiang/qtwj/zfxxgk_gknrz.shtml"],
            ['疆维吾尔自治区发展和改革委员会', "https://xjdrc.xinjiang.gov.cn/xjfgw/c108361/zfxxgk_gknrz.shtml"],
            ['新疆维吾尔自治区科学技术厅', "https://kjt.xinjiang.gov.cn/kjt/gfxwj/zfxxgk_gknrz.shtml"],
            ['新疆维吾尔自治区科学技术厅', "https://kjt.xinjiang.gov.cn/kjt/qtzcwj/zfxxgk_gknrz.shtml"],
            ['新疆维吾尔自治区工业和信息化厅', "https://gxt.xinjiang.gov.cn/gxt/gfxwj/zfxxgk_gknrz.shtml"],
            ['新疆维吾尔自治区工业和信息化厅', "https://gxt.xinjiang.gov.cn/gxt/gfxwji/list.shtml"],
            ['新疆维吾尔自治区民政厅', "https://mzt.xinjiang.gov.cn/xjmzt/c113003/zfxxgk_list.shtml"],
            ['新疆维吾尔自治区民政厅', "https://mzt.xinjiang.gov.cn/xjmzt/c113004/zfxxgk_list.shtml"],
            ['新疆维吾尔自治区人力资源和社会保障厅', "https://rst.xinjiang.gov.cn/xjrst/gfxwjm/zfxxgk_gknrz.shtml"],
            ['新疆维吾尔自治区人力资源和社会保障厅', "https://zjt.xinjiang.gov.cn/xjzjt/c113288/zwgk_list_search.shtml"],
            ['新疆维吾尔自治区人力资源和社会保障厅', "https://zjt.xinjiang.gov.cn/xjzjt/c113288/zwgk_list_search.shtml"],
            ['新疆维吾尔自治区农业农村厅', "https://nynct.xinjiang.gov.cn/xjnynct/c113595/zwgk_list.shtml"],
            ['新疆维吾尔自治区商务厅', "https://swt.xinjiang.gov.cn/xjswt/c114346/zwgk_list.shtml"],
            ['新疆维吾尔自治区文化和旅游厅', "https://wlt.xinjiang.gov.cn/wlt/zcwj/zfxxgk_list.shtml"],
            ['新疆维吾尔自治区市场监督管理局', "https://scjgj.xinjiang.gov.cn/xjaic/zdwjhb/zfxxgk_gknrz.shtml"],
            ['新疆维吾尔自治区市场监督管理局', "https://scjgj.xinjiang.gov.cn/xjaic/xzgfxwj/zfxxgk_gknrz.shtml"],
            ['新疆维吾尔自治区地方金融监督管理局', "https://jrjgj.xinjiang.gov.cn/jrb/zcwjgfx/newzfxxgk.shtml"],
        ]:
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': {'source': source}})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath("//td[@class='tal']//a[contains(@href, '.shtm') or @title]/ancestor::td[string-length(string(.))>=5] | "
                                   "//tr[@id='line63804_0']//td//a[contains(@href, '.shtm') or @title]/ancestor::td[string-length(string(.))>=5] | "
                                   "//ul[@class='list pt20' or @class='innerList']//li//a[contains(@href, '.shtm') or @title]/ancestor::li[string-length(string(.))>=5] | "
                                   "//div[@class='gknr_list']//dd//a[contains(@href, '.shtm') or @title]/ancestor::dd[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            # item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or 0
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace(".shtml", f"_{page_num}.shtml")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_xjwwezzqrmzf_f363_policy".split())
